import requests
import base64 #百度语音要求对本地语音二进制数据进行base64编码

#组装url获取token，详见文档
base_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
APIKey = "oPWSUgbtst7zGQT2C6FIVPB9"
SecretKey = "8jVLT5GfnT7lzIg3nCGQDPMrnjZ8RRIR"

HOST = base_url % (APIKey, SecretKey)

def getToken(host):
    res = requests.post(host)
    return res.json()['access_token']



def speech2text(speech_data, token, dev_pid=1536):
    FORMAT = 'wav'
    RATE = '16000'
    CHANNEL = 1
    CUID = '********'
    SPEECH = base64.b64encode(speech_data).decode('utf-8')

    data = {
        'format': FORMAT,
        'rate': RATE,
        'channel': CHANNEL,
        'cuid': CUID,
        'len': len(speech_data),
        'speech': SPEECH,
        'token': token,
        'dev_pid':dev_pid
    }
    url = 'https://vop.baidu.com/server_api'
    headers = {'Content-Type': 'application/json'}
    print('正在识别...')
    r = requests.post(url, json=data, headers=headers)
    Result = r.json()
    if 'result' in Result:
        return Result['result'][0]
    else:
        return Result
    print(Result)
def get_audio(file):
    with open(file, 'rb') as f:
        data = f.read()
    return data

TOKEN = getToken(HOST)
speech = get_audio("./speech.wav")
result = speech2text(speech, TOKEN)
print(result)